package com.scheduler.activities;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.scheduler.database.RegistrationFunctions;
import com.scheduler.helper.Constants;
import com.scheduler.helper.Messages;



public class RegistrationActivity extends Activity implements OnClickListener {
	// Screen variables
	EditText emailId;
	EditText fullName;
	EditText password;
	EditText confirmPassword;
	Button buttonRegister;
	Button buttonCancel;

	String returnCount, returnString;

	// Dialogue variable
	private static final int PASSWORD_MISMATCH = 10;
	private static final int INVALID_EMAIL = 11;
	private static final int FIELD_BLANK = 12;
	private static final int EMAIL_NOT_AVAILABLE = 13;
	private static final int PASSWORD_LENGTH_INVALID = 14;
	private static final int NAME_INVALID = 15;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO what is this Strict Mode
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());

		super.onCreate(savedInstanceState);
		setContentView(R.layout.registration);

		// Find the value in the edit text
		emailId = (EditText) findViewById(R.id.editEmailId);
		fullName = (EditText) findViewById(R.id.editFullName);
		password = (EditText) findViewById(R.id.editPassword);
		confirmPassword = (EditText) findViewById(R.id.editConfirmPassword);

		// FInd the buttons on the screen
		buttonRegister = (Button) findViewById(R.id.buttonRegister);
		buttonCancel = (Button) findViewById(R.id.buttonCancel);

		// On click of register check the values entered and register the user
		buttonRegister.setOnClickListener(this);

		buttonCancel.setOnClickListener(this);

	}

	@SuppressWarnings("deprecation")
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.buttonRegister:

			String userPassword = password.getText().toString();
			String userFullName = fullName.getText().toString();
			String userEmail = emailId.getText().toString();
			String userConfirmPassword = confirmPassword.getText().toString();

			Log.d(Constants.LOGGER_REGISTRATION_TAG,
					"Onclick of Register: Email Id: "
							+ password.getText().toString() + " Password :"
							+ confirmPassword.getText().toString());

			// Check if all the field variables are available to register
			boolean fieldBlank = false;
			if (userPassword.trim().equals("")
					|| userFullName.trim().equals("")
					|| userEmail.trim().equals("")
					|| userConfirmPassword.trim().equals("")) {

				Log.d(Constants.LOGGER_REGISTRATION_TAG, "Fields left blank");

				fieldBlank = true;
			}

			// Pattern foe email syntax matching
			Pattern p = Pattern
					.compile("^[_a-z0-9-]+(\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,4})$");
			Matcher m = p.matcher(userEmail);
			
			//Patter matching for Name
			Pattern userNamePattern = Pattern.compile("^[a-zA-Z]$");
			Matcher userNameMatcher = userNamePattern.matcher(userFullName);
			
			//Number of charecters in the password
			boolean passwordLengthValid = true;
			if(userPassword.length() < 6)
			{
				passwordLengthValid = false;
			}

			Log.d(Constants.LOGGER_REGISTRATION_TAG,
					"Pre condition values: email match - " + m.matches()
							+ "blank field - " + fieldBlank + "Password Valid - " + passwordLengthValid);

			// Check if the old and the new passwords are same
			if (userPassword.equalsIgnoreCase(userConfirmPassword)
					&& m.matches() && !fieldBlank && passwordLengthValid) {
				// Create the database function object
				RegistrationFunctions registrationFunction = new RegistrationFunctions();

				Log.d(Constants.LOGGER_REGISTRATION_TAG,
						"All conditions good, check for uniquness of email id");
				// Get the detail of all the items in the screen and insert it
				// into the database
				String result = registrationFunction
						.checkEmailIdUnique(userEmail);
				result = result.replaceAll("\\s+", "");
				
				if (result.equals("0")) {
					showDialog(EMAIL_NOT_AVAILABLE);
				} else {
					// else insert a new record
					result = registrationFunction.registerUser(userEmail,
							userFullName, userPassword);
					result = result.replaceAll("\\s+", "");

					// Start the new activity
					Intent myIntent = new Intent(RegistrationActivity.this,
							HomeActivity.class);
					RegistrationActivity.this.startActivity(myIntent);

				}

			} else {
				if (fieldBlank) {
					Log.d(Constants.LOGGER_REGISTRATION_TAG,
							"Field blank dialogue");
					showDialog(FIELD_BLANK);
				} else if(userNameMatcher.matches()){
					Log.d(Constants.LOGGER_REGISTRATION_TAG,
							"User Name invalid dialogue");
					showDialog(NAME_INVALID);
				}else if (m.matches()) {
					Log.d(Constants.LOGGER_REGISTRATION_TAG,
							"Password mismatch dialogue");
					showDialog(PASSWORD_MISMATCH);
				} else if(passwordLengthValid){
					Log.d(Constants.LOGGER_REGISTRATION_TAG,
							"Password length invalid dialogue");
					showDialog(PASSWORD_LENGTH_INVALID);
				}else {
					Log.d(Constants.LOGGER_REGISTRATION_TAG,
							"Email Id not available dialogue");
					showDialog(INVALID_EMAIL);
				}
			}

			break;

		case R.id.buttonCancel:
			//Clear the fields filled by the user. if any
			
			//Finish the activity
			Intent myIntent = new Intent(RegistrationActivity.this,
					UserLoginActivity.class);
			RegistrationActivity.this.startActivity(myIntent);
			RegistrationActivity.this.finish();
			break;
		}

	}

	@SuppressWarnings("deprecation")
	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case PASSWORD_MISMATCH:
			// Create out AlterDialog
			Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(Messages.PASSWORD_MISMATCH_HEAD);
			builder.setMessage(Messages.PASSWORD_MISMATCH);
			builder.setCancelable(true);
			builder.setNegativeButton("Dismiss", new CancelOnClickListener());
			AlertDialog dialog = builder.create();
			dialog.show();
			break;
		case INVALID_EMAIL:
			// Create out AlterDialog
			Builder builder1 = new AlertDialog.Builder(this);
			builder1.setMessage(Messages.INVALID_EMAIL_HEAD);
			builder1.setMessage(Messages.INVALID_EMAIL_FORMAT);
			builder1.setCancelable(true);
			builder1.setNegativeButton("Dismiss", new CancelOnClickListener());
			AlertDialog dialog1 = builder1.create();
			dialog1.show();
			break;
		case FIELD_BLANK:
			// Create out AlterDialog
			Builder builder2 = new AlertDialog.Builder(this);
			builder2.setMessage(Messages.BLANK_FIELD_HEAD);
			builder2.setMessage(Messages.BLANK_FIELD);
			builder2.setCancelable(true);
			builder2.setNegativeButton("Dismiss", new CancelOnClickListener());
			AlertDialog dialog2 = builder2.create();
			dialog2.show();
			break;
		case EMAIL_NOT_AVAILABLE:
			// Create out AlterDialog
			Builder builder3 = new AlertDialog.Builder(this);
			builder3.setMessage(Messages.EMAIL_UNAVAILABLE_HEAD);
			builder3.setMessage(Messages.EMAIL_UNAVAILABLE);
			builder3.setCancelable(true);
			builder3.setNegativeButton("Dismiss", new CancelOnClickListener());
			AlertDialog dialog3 = builder3.create();
			dialog3.show();
			break;
		case PASSWORD_LENGTH_INVALID:
			// Create out AlterDialog
			Builder builder4 = new AlertDialog.Builder(this);
			builder4.setMessage(Messages.PASSWORD_LENGTH_INVALID_HEAD);
			builder4.setMessage(Messages.PASSWORD_LENGTH_INVALID);
			builder4.setCancelable(true);
			builder4.setNegativeButton("Dismiss", new CancelOnClickListener());
			AlertDialog dialog4 = builder4.create();
			dialog4.show();
			break;
		case NAME_INVALID:
			// Create out AlterDialog
			Builder builder5 = new AlertDialog.Builder(this);
			builder5.setMessage(Messages.NAME_INVALID_HEAD);
			builder5.setMessage(Messages.NAME_INVALID);
			builder5.setCancelable(true);
			builder5.setNegativeButton("Dismiss", new CancelOnClickListener());
			AlertDialog dialog5 = builder5.create();
			dialog5.show();
			break;
		}
		return super.onCreateDialog(id);
	}

	private final class CancelOnClickListener implements
			DialogInterface.OnClickListener {
		public void onClick(DialogInterface dialog, int which) {
			// Do nothing, as it goes back to login screen
		}
	}
	
	
	/*private void clearFields(){
		
		ViewGroup group = (ViewGroup)findViewById(R.id.);
		for (int i = 0, count = group.getChildCount(); i < count; ++i) {
		    View view = group.getChildAt(i);
		    if (view instanceof EditText) {
		        ((EditText)view).setText("");
		    }
		}
	}*/
}